package cn.cvs.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {

    private static SqlSessionFactory factory;

    static {
        String resouce = "mybatis-config.xml";

        try {
            // 读取配置文件
            InputStream is = Resources.getResourceAsStream(resouce);
            //创建 SqlSessionFactoryBuilder
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //创建 SqlSessionFactory
            factory = builder.build(is);

        } catch (IOException e) {
            throw new RuntimeException("创建SqlSessionFactory失败");
        }


    }

    /**
     * 获取 SqlSession 对象
     * @return
     */
    public static SqlSession createSqlSession(){
        return factory.openSession();
    }

    /**
     * 关闭 SqlSession
     * @param sqlSession
     */
    public static void closeSqlSession(SqlSession sqlSession){
        if (sqlSession != null){
            sqlSession.close();
        }
    }
}
